package com.think.cloud.thinkshop.mall.service.productgroup.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.think.cloud.thinkshop.mall.controller.admin.productgroup.vo.*;
import com.think.cloud.thinkshop.mall.convert.productgroup.ProductGroupConvert;
import com.think.cloud.thinkshop.mall.domain.ProductGroup;
import com.think.cloud.thinkshop.mall.domain.ProductGroupRelation;
import com.think.cloud.thinkshop.mall.enums.group.IntelligentGroupEnum;
import com.think.cloud.thinkshop.mall.mapper.ProductGroupMapper;
import com.think.cloud.thinkshop.mall.mapper.ProductGroupRelationMapper;
import com.think.cloud.thinkshop.mall.service.product.IProductService;
import com.think.cloud.thinkshop.mall.service.productgroup.IProductGroupService;
import com.think.common.core.exception.enums.ErrorCode;
import com.think.common.core.exception.util.ServiceExceptionUtil;
import com.think.common.core.utils.PageUtils;
import com.think.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品分组Service业务层处理
 *
 * @author zkthink
 * @date 2024-05-10
 */
@Service
public class ProductGroupServiceImpl implements IProductGroupService {
    @Autowired
    private ProductGroupMapper productGroupMapper;
    @Autowired
    private ProductGroupRelationMapper productGroupRelationMapper;
    @Autowired
    private IProductService iProductService;

    /**
     * 查询商品分组
     *
     * @param groupId 商品分组主键
     * @return 商品分组
     */
    @Override
    public ProductGroupDetailRespVO selectProductGroupByGroupId(Long groupId) {
        ProductGroupDetailRespVO vo = ProductGroupConvert.INSTANCE.convert1(productGroupMapper.selectById(groupId));
        List<ProductGroupRelation> productGroupRelationList =
                productGroupRelationMapper.selectList(new LambdaQueryWrapper<ProductGroupRelation>()
                        .eq(ProductGroupRelation::getGroupId, groupId));
        if (CollectionUtil.isNotEmpty(productGroupRelationList)) {
            vo.setProductIds(productGroupRelationList.stream().map(ProductGroupRelation::getProductId).collect(Collectors.toList()));
        }
        return vo;
    }

    /**
     * 查询商品分组列表
     *
     * @param vo
     * @return 商品分组
     */
    @Override
    public TableDataInfo selectProductGroupList(ProductGroupPageReqVO vo) {
        List<ProductGroup> productGroups = productGroupMapper.selectList(vo);
        List<ProductGroupPageRespVO> vos = ProductGroupConvert.INSTANCE.convertList(productGroups);
        // 查询关联商品数量
        if (CollectionUtil.isNotEmpty(vos)) {
            List<Long> groupIds = vos.stream().map(ProductGroupPageRespVO::getGroupId).collect(Collectors.toList());
            List<ProductGroupPageRespVO> relationCountList = productGroupRelationMapper.getRelationCount(groupIds);
            Map<Long, Integer> relationCountMap = relationCountList.stream()
                    .collect(Collectors.toMap(ProductGroupPageRespVO::getGroupId, ProductGroupPageRespVO::getRelationCount));
            vos.forEach(res -> {
                res.setRelationCount(ObjectUtil.isNotNull(relationCountMap.get(res.getGroupId())) ?
                        relationCountMap.get(res.getGroupId()) : 0);
            });
        }
        return new TableDataInfo(vos, PageUtils.getTotal(productGroups));
    }

    /**
     * 新增商品分组
     *
     * @param vo 商品分组
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertProductGroup(SaveProductGroupReqVO vo) {
        ProductGroup productGroup = ProductGroupConvert.INSTANCE.convert(vo);
        if (!IntelligentGroupEnum.HAND.getType().equals(vo.getType())) {
            productGroup.setConditionJson(JSONObject.toJSONString(vo.getIntelligent()));
            vo.setProductIds(iProductService.intelligentSearch(vo.getIntelligent()));
        }
        productGroupMapper.insert(productGroup);
        if (CollectionUtil.isNotEmpty(vo.getProductIds())) {
            // 保存分组关联
            List<ProductGroupRelation> productGroupRelationList =
                    vo.getProductIds().stream().map(productId -> ProductGroupRelation.builder()
                            .productId(productId).groupId(productGroup.getGroupId()).build()
                    ).collect(Collectors.toList());
            productGroupRelationMapper.batchInsert(productGroupRelationList);
        } else if (IntelligentGroupEnum.INTELLIGENT.getType().equals(vo.getType())) {
            throw ServiceExceptionUtil.exception(ErrorCode.INTELLIGENT_GROUPING_LOGIC_ERROR);
        }
    }

    /**
     * 修改商品分组
     *
     * @param vo
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductGroup(UpdateProductGroupReqVO vo) {
        ProductGroup productGroup = ProductGroupConvert.INSTANCE.convert(vo);
        if (!IntelligentGroupEnum.HAND.getType().equals(vo.getType())) {
            productGroup.setConditionJson(JSONObject.toJSONString(vo.getIntelligent()));
            vo.setProductIds(iProductService.intelligentSearch(vo.getIntelligent()));
        }
        productGroupMapper.updateById(productGroup);
        // 删除旧分组关联
        productGroupRelationMapper.delete(new LambdaQueryWrapper<ProductGroupRelation>()
                .eq(ProductGroupRelation::getGroupId, vo.getGroupId()));
        if (CollectionUtil.isNotEmpty(vo.getProductIds())) {
            // 保存分组关联
            List<ProductGroupRelation> productGroupRelationList =
                    vo.getProductIds().stream().map(productId -> ProductGroupRelation.builder()
                            .productId(productId).groupId(productGroup.getGroupId()).build()
                    ).collect(Collectors.toList());
            productGroupRelationMapper.batchInsert(productGroupRelationList);
        } else if (IntelligentGroupEnum.INTELLIGENT.getType().equals(vo.getType())) {
            throw ServiceExceptionUtil.exception(ErrorCode.INTELLIGENT_GROUPING_LOGIC_ERROR);
        }

    }

    /**
     * 批量删除商品分组信息
     *
     * @param groupIds 主键集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(List<Long> groupIds) {
        // 删除分组关联
        productGroupRelationMapper.delete(new LambdaQueryWrapper<ProductGroupRelation>()
                .in(ProductGroupRelation::getGroupId, groupIds));
        return productGroupMapper.deleteBatchIds(groupIds);
    }

    @Override
    public void removeProduct(RemoveProductReqVO vo) {
        productGroupRelationMapper.delete(new LambdaQueryWrapper<ProductGroupRelation>()
                .eq(ProductGroupRelation::getGroupId, vo.getGroupId())
                .in(ProductGroupRelation::getProductId, vo.getProductIds()));
    }

    @Override
    public List<Long> findGroupIdByName(List<String> names) {
        List<ProductGroup> productGroups = productGroupMapper.selectList(
                Wrappers.<ProductGroup>lambdaQuery().in(ProductGroup::getName, names)
        );
        return productGroups.stream().map(ProductGroup::getGroupId).collect(Collectors.toList());
    }
}
